package 企业微信;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

/**
 * @description: 企业微信推送
 * @Author lxs
 * @Date 2025/4/24 14:51
 */
public class WeChatWorkPusher {

    // 替换为你自己的企业ID、应用ID和Secret
    private static final String CORP_ID = "你的企业ID";
    private static final String CORP_SECRET = "你的应用Secret";
    private static final String AGENT_ID = "1000002";  // 应用AgentId
    private static final String USER_ID = "目标用户的UserID"; // 可设置多个 userID 用 | 分隔

    // 获取 access_token 的 URL
    private static final String TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    // 发送消息的 URL
    private static final String MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    public static void main(String[] args) throws IOException {
        String accessToken = getAccessToken();
        if (accessToken != null) {
            sendTextMessage(accessToken, "企业微信Java推送测试：Hello, 企业微信！");
        }
    }

    /**
     * 获取 access_token
     */
    public static String getAccessToken() throws IOException {
        OkHttpClient client = new OkHttpClient();

        HttpUrl url = HttpUrl.parse(TOKEN_URL).newBuilder()
                .addQueryParameter("corpid", CORP_ID)
                .addQueryParameter("corpsecret", CORP_SECRET)
                .build();

        Request request = new Request.Builder().url(url).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println("获取access_token失败");
            return null;
        }

        String body = response.body().string();
        JSONObject json = JSONObject.parseObject(body);
        System.out.println("获取Token响应: " + json);

        return json.getString("access_token");
    }

    /**
     * 推送文本消息
     */
    public static void sendTextMessage(String accessToken, String content) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 构造请求消息 JSON
        JSONObject message = new JSONObject();
        message.put("touser", USER_ID);          // 发送给指定用户
        message.put("msgtype", "text");          // 消息类型
        message.put("agentid", AGENT_ID);        // 应用ID

        JSONObject text = new JSONObject();
        text.put("content", content);            // 文本内容
        message.put("text", text);

        message.put("safe", 0);                  // 表示是否保密消息，0 表示否

        RequestBody body = RequestBody.create(
                message.toJSONString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url(MESSAGE_URL + accessToken)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();
        String responseStr = response.body().string();
        System.out.println("消息发送响应: " + responseStr);
    }
}
